# Makefile for STM32F407 RSA Batch Processing (Semihosting)
# 使用方法：
#   make                      # 编译batch版本
#   make clean                # 清理
#   make flash                # 烧录到STM32

# 工具链设置
PREFIX = arm-none-eabi-
CC = $(PREFIX)gcc
AS = $(PREFIX)as
CP = $(PREFIX)objcopy
SZ = $(PREFIX)size

# 项目名称
PROJECT = rsa_batch

# 编译选项
MCU = -mcpu=cortex-m4 -mthumb -mfloat-abi=soft
FPU = -mfpu=fpv4-sp-d16

# 编译标志
CFLAGS = $(MCU) $(FPU) -std=gnu11 -Wall -fdata-sections -ffunction-sections
ASFLAGS = $(MCU) $(FPU)
LDFLAGS = $(MCU) $(FPU) -specs=nano.specs -T$(LDSCRIPT) -Wl,-Map=$(BUILD_DIR)/$(PROJECT).map,--cref -Wl,--gc-sections

# 包含目录
INCLUDES = -I.

# 源文件
C_SOURCES = \
main.c \
syscalls_semihosting.c \
stm32f4xx_rsa.c \
rsa_impl.c \
system_stm32f4xx.c

# 汇编源文件
ASM_SOURCES = \
startup_stm32f407xx.s

# 链接脚本
LDSCRIPT = STM32F407VGTx_FLASH.ld

# 构建目录
BUILD_DIR = build

# 目标文件
OBJECTS = $(addprefix $(BUILD_DIR)/,$(notdir $(C_SOURCES:.c=.o)))
OBJECTS += $(addprefix $(BUILD_DIR)/,$(notdir $(ASM_SOURCES:.s=.o)))

# 默认目标
all: $(BUILD_DIR)/$(PROJECT).elf

# 创建构建目录
$(BUILD_DIR):
	mkdir -p $@

# 编译C源文件
$(BUILD_DIR)/%.o: %.c Makefile | $(BUILD_DIR)
	$(CC) -c $(CFLAGS) $(INCLUDES) -Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@

# 编译汇编源文件
$(BUILD_DIR)/%.o: %.s Makefile | $(BUILD_DIR)
	$(AS) $(ASFLAGS) -c $< -o $@

# 链接
$(BUILD_DIR)/$(PROJECT).elf: $(OBJECTS) Makefile
	$(CC) $(OBJECTS) $(LDFLAGS) -o $@
	$(SZ) $@

# 生成二进制文件
$(BUILD_DIR)/$(PROJECT).bin: $(BUILD_DIR)/$(PROJECT).elf
	$(CP) -O binary -S $< $@

# 生成十六进制文件
$(BUILD_DIR)/$(PROJECT).hex: $(BUILD_DIR)/$(PROJECT).elf
	$(CP) -O ihex -S $< $@

# 简化的目标名称
bin: $(BUILD_DIR)/$(PROJECT).bin
hex: $(BUILD_DIR)/$(PROJECT).hex

# 清理
clean:
	rm -rf $(BUILD_DIR)

# 烧录到STM32 (需要OpenOCD)
flash: $(BUILD_DIR)/$(PROJECT).bin
	openocd -f interface/stlink.cfg -f target/stm32f4x.cfg -c "program $(BUILD_DIR)/$(PROJECT).bin verify reset exit"

# 调试 (需要OpenOCD)
debug: $(BUILD_DIR)/$(PROJECT).elf
	openocd -f interface/stlink.cfg -f target/stm32f4x.cfg -c "program $(BUILD_DIR)/$(PROJECT).elf verify reset exit"

# 帮助
help:
	@echo "=== STM32 AES Batch Processing 编译系统 ==="
	@echo ""
	@echo "可用的目标:"
	@echo "  make         - 编译批处理固件 (main_batch.c + semihosting)"
	@echo "  clean        - 清理构建文件"
	@echo "  bin          - 生成二进制文件"
	@echo "  hex          - 生成十六进制文件"
	@echo "  flash        - 烧录到STM32"
	@echo "  help         - 显示此帮助信息"
	@echo ""
	@echo "输出文件:"
	@echo "  build/$(PROJECT).elf  - ELF可执行文件（用于QEMU）"
	@echo "  build/$(PROJECT).bin  - 二进制文件（用于烧录）"
	@echo ""
	@echo "示例："
	@echo "  make clean && make"
	@echo "  qemu-system-arm -M netduinoplus2 -nographic -kernel build/$(PROJECT).elf -semihosting"

.PHONY: all clean bin hex flash debug help
